<template>
  <div>
    <div>
      <div v-for="(item, index) of msgList" :key="index">
        <span>{{ item.name === uname ? '我' : item.name }}</span>
        <span>({{ new Date(item.date) }}):</span>
        <p>{{ item.msg }}</p>
      </div>
    </div>
    <Input v-model="msg" placeholder="请输入..." style="width: 300px" />
    <Button type="primary" @click="send">发送消息</Button>
    <Input v-model="uname" placeholder="昵称" style="width: 300px" />
    <!-- <Button type="primary" @click="login">登录</Button>
    <Button type="primary" @click="testToken">测试需要携带token</Button> -->
  </div>
</template>

<script>
import ws from '../../web-socket';

const options = {
  code: 1,
};

export default {
  name: 'homePage',
  data() {
    return {
      msg: '',
      uname: '我是GG',
      msgList: [],
    };
  },
  mounted() {
    // demo  get请求和post请求有2个区别method 和参数(params | data)
    // this.$ajax({
    //   url: '/api/user/queryUserName',
    //   params: {
    //     userName: 'root',
    //   },
    // }).then(console.log)
    //   .catch(console.error);

    // this.$ajax({
    //   url: '/api/user/login',
    //   method: 'post',
    //   data: {
    //     userName: 'root',
    //     password: '123456',
    //   },
    // }).then(console.log)
    //   .catch(console.error);
    this.init();
  },
  methods: {
    init() {
      ws.addMessageQueue({
        options,
        callback: (data) => {
          this.msgList.push(data);
        },
      });
    },
    send() {
      ws.send({
        options,
        data: {
          msg: this.msg,
          name: this.uname,
          date: new Date().getTime(),
        },
      });
    },
    login() {
      this.$ajax({
        url: '/api/user/login',
        method: 'post',
        data: {
          userName: 'root',
          password: '123456',
        },
      }).then(console.log)
        .catch(console.error);
    },
    testToken() {
      this.$ajax({
        url: '/api/test/testToken',
        method: 'get',
        data: {
          userName: 'root',
          password: '123456',
        },
      }).then(console.log)
        .catch(console.error);
    },
  },
};
</script>

<style scoped>
</style>
